<script setup lang="ts">
  import routeComponentName from '@/config/route-component-name'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { useRoute, useRouter } from 'vue-router'
  import SparePartSelectModal from './components/spare-part-select-modal/spare-part-select-modal.vue'
  import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import { useUserStore } from '@/store/modules/user'
  import debounce from 'lodash/debounce'
  import useNetworkListService from '@/services/module/network/useNetworkListService'
  import { cloneDeep } from 'lodash'
  import { SparePartApplyFormMaterial } from './types'
  import {
    useCreateSparePartApplyCheckStockService,
    useSparePartApplyForm,
  } from '@/services/module/store/useSparePartApplyFormService'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import {
    ElMessageBox,
    FormInstance,
    TableColumnCtx,
    UploadFile,
    UploadRawFile,
  } from 'element-plus'
  import useSparePartApplyDetail from '@/services/module/store/useSparePartApplyDetail'
  import { useGetNetworkWarehouse } from '@/services/pages/storage/useWarehouse'
  import useCurrentRoleStore from '@/store/modules/current-role'
  import { fileUpload } from '@/api/upload'
  import { useNetworkAmountLimitService } from '@/services/module/network/useNetworkAmountLimitService'

  const { networkAmountLimit, getNetworkAmount } = useNetworkAmountLimitService()
  const { currentRole } = useCurrentRoleStore()
  const { warehouse, getWarehouse } = useGetNetworkWarehouse()
  const { sparePartApplyDetail, getSparePartApplyDetailLoading, getSparePartApplyDetail } =
    useSparePartApplyDetail()
  const { stockCheckForm, stockCheckResult, stockCheckLoading, stockCheck } =
    useCreateSparePartApplyCheckStockService()
  const { networkList, getNetworkListParam, getNetworkListLoading, getNetworkList } =
    useNetworkListService()
  const { form, formSaveLoading, submit, resetForm } = useSparePartApplyForm()

  defineOptions({
    name: routeComponentName.storage.sparePartApply.form,
  })

  const fileList = ref<Array<{ file: UploadRawFile | null; url: string }>>([])

  const route = useRoute()
  const router = useRouter()

  const userStore = useUserStore()
  const tagsViewStore = useTagsViewStore()

  const allQtyInputPopoverVisible = ref(false)
  const sparePartSelectModalVisible = ref(false)
  const receiveStoreSelectPopoverVisible = ref(false)
  const networkSelectPopoverVisible = ref(false)
  const networkCodeSelectPopoverVisible = ref(false)

  const allApplyQty = ref(1)

  const address = computed(() => {
    return {
      province: form.value.province,
      city: form.value.city,
      area: form.value.area,
      town: form.value.town,
    }
  })

  const materialList = ref<Array<SparePartApplyFormMaterial>>([])
  const materialSpareIdAndSpecIdList = computed(() => {
    return materialList.value.map((item) => {
      return {
        spareId: item.spareId,
        specId: item.specId,
        isBom: item.isBom,
      }
    })
  })

  const selectShowInfo = ref<{
    receiveStoreName: string
    sendStoreName: string
    networkName: string
    freeAmount: number | null
    networkCode: string
  }>({
    receiveStoreName: '',
    sendStoreName: '',
    networkName: '',
    freeAmount: null,
    networkCode: '',
  })

  const formInstance = ref<FormInstance | null>(null)
  const formRules = computed(() => {
    const result: Record<
      string,
      Array<{
        required?: boolean
        message?: string
        trigger: Array<'change' | 'blur'>
        validator?: (rule: any, value: any, callback: any) => void
      }>
    > = {
      receiveStoreId: [{ required: true, message: '请选择收货仓库', trigger: ['change', 'blur'] }],
      contactName: [{ required: true, message: '请输入联系人名称', trigger: ['change', 'blur'] }],
      contactPhone: [
        { required: true, message: '请输入联系人手机号', trigger: ['change', 'blur'] },
      ],
      address: [
        {
          validator: (rule: any, value: any, callback: any) => {
            if (form.value.province && form.value.city && form.value.area) {
              callback()
            }
            callback(new Error('请选择收货地址'))
          },
          trigger: ['change', 'blur'],
        },
      ],
      detailAddress: [{ required: true, message: '请输入详细地址', trigger: ['change', 'blur'] }],
    }

    if (userStore.$state.userInfo.networkId) {
      result.networkId = [{ required: true, message: '请选择经销商', trigger: ['change', 'blur'] }]
    }

    return result
  })

  const closeThisPage = (isUpdate = false) => {
    resetForm()
    tagsViewStore.delView(route.path)
    router.push({
      path: '/storage/spare/part/apply/list',
      query: { isUpdate: isUpdate ? 'true' : 'false' },
    })
  }

  const _submit = async () => {
    const res = await submit()
    if (res) {
      if (res.code === 20000) {
        HMessage.success('保存成功')
        closeThisPage(true)
        return
      }

      HMessageBox.error(res.message)
      return
    }
  }

  const onSubmitClick = async (status: 1 | 2) => {
    if (!formInstance.value) {
      return false
    }

    try {
      await formInstance.value.validate()

      form.value.status = status
      form.value.materialApplyParamList = materialList.value.map((item) => {
        return {
          id: item.id,
          spareId: item.spareId,
          spareCode: item.spareCode,
          qty: item.applyQty,
          actualQty: item.actualSendQty,
          materialRemark: item.remark,
          urgency: item.urgentLevel,
          isSufficient: item.stock >= item.applyQty ? 1 : 0,
          price: item.price,
          isBoom: item.isBom ? 1 : 0,
          warehouse: item.warehouse,
        }
      })

      if (materialList.value.length <= 0) {
        HMessageBox.error('请添加配件')
        return
      }

      if (form.value.type == 3 && fileList.value.length <= 0) {
        HMessageBox.error('请上传附件')
        return
      }

      if (fileList.value.length > 1) {
        const fileRawList = fileList.value.filter((item) => item.file).map((item) => item.file)
        const res = await fileUpload(fileRawList as Array<UploadRawFile>)
        if (res.data.code === 20000) {
          fileList.value = fileList.value.filter((item) => !item.file)
          res.data.data.rows.forEach((url) => {
            fileList.value.push({
              file: null,
              url,
            })
          })
        } else {
          HMessageBox.error(res.data.message)
        }
      }

      form.value.attachmentParamList = fileList.value.map((item) => item.url)

      if (status === 1) {
        await _submit()
        return
      }

      if (userStore.userInfo.networkId) {
        stockCheckForm.value.networkId = userStore.userInfo.networkId
        form.value.networkId = userStore.userInfo.networkId
      } else {
        stockCheckForm.value.networkId = form.value.networkId
      }

      form.value.materialApplyParamList.forEach((item) => {
        stockCheckForm.value.materialQty[item.spareCode] = item.qty
      })
      const errMsg = await stockCheck()
      if (errMsg) {
        HMessageBox.error(errMsg)
        return
      }

      if (currentRole && currentRole.roleType !== 1) {
        form.value.type = stockCheckResult.value.type
      }
      const tipMsg: Array<string> = []
      if (stockCheckResult.value.isSufficient === 0) {
        tipMsg.push(stockCheckResult.value.difference + '申请量大于可用量')
      }

      if (currentRole && currentRole.roleType === 2 && stockCheckResult.value.type === 1) {
        tipMsg.push('该申请单为收费单据')
      }

      if (tipMsg.length > 0) {
        ElMessageBox({
          title: '提示',
          message: tipMsg.join('并且') + '，是否继续提交？',
          showCancelButton: true,
          type: 'warning',
          autofocus: false,
        }).then(() => {
          _submit()
        })
        return
      }

      _submit()
    } catch (e) {
      // e
    }
  }

  const handleDocumentClick = () => {
    allQtyInputPopoverVisible.value = false
    receiveStoreSelectPopoverVisible.value = false
    networkCodeSelectPopoverVisible.value = false
  }

  const onQtyMultipleClick = () => {
    allQtyInputPopoverVisible.value = !allQtyInputPopoverVisible.value
    if (allQtyInputPopoverVisible.value) {
      document.addEventListener('click', handleDocumentClick)
    }
  }

  const onQtyMultipleConfirmClick = () => {
    allQtyInputPopoverVisible.value = false
    materialList.value = materialList.value.map((item, index) => {
      item.applyQty = allApplyQty.value
      handleApplyQtyChange(index)
      return item
    })
    allApplyQty.value = 1
  }

  const handleSingleAddressChange = (value: {
    province: string
    city: string
    area: string
    town: string
  }) => {
    form.value.province = value.province
    form.value.city = value.city
    form.value.area = value.area
    form.value.town = value.town
  }

  const handleNetworkInput = debounce(() => {
    getNetworkListParam.value.networkSearch = selectShowInfo.value.networkName
    getNetworkList().then(() => {
      networkSelectPopoverVisible.value = true
      document.addEventListener('click', handleDocumentClick)
    })
  }, 300)

  const handleNetworkCodeInput = debounce(() => {
    getNetworkListParam.value.networkSearch = selectShowInfo.value.networkCode
    getNetworkList().then(() => {
      networkCodeSelectPopoverVisible.value = true
      document.addEventListener('click', handleDocumentClick)
    })
  }, 300)

  const handleSparePartSelectModalGoodSelect = (data: {
    goodList: Array<GoodItem>
    bomList: Array<GoodAPIResponse.GoodBomChildListItem>
  }) => {
    const _formMaterialList: SparePartApplyFormMaterial[] = []

    const addFormMaterial = (good: {
      code: string
      id: string
      name: string
      specId: string
      specName: string
      type: string
      unit: string
      price: number
      storeQty: number
      freezeQty: number
      isBom: boolean
      warehouse: string
      warehouseList: Array<string>
    }) => {
      _formMaterialList.push({
        spareCode: good.code,
        spareId: good.id,
        spareName: good.name,
        applyQty: 1,
        actualSendQty: 0,
        specId: good.specId,
        specName: good.specName,
        type: good.type,
        unit: good.unit,
        price: good.price,
        remark: '',
        urgentLevel: 1,
        stock: good.storeQty - good.freezeQty,
        stockTipPopoverVisible: false,
        id: '',
        isBom: good.isBom,
        warehouse: good.warehouse,
        warehouseList: good.warehouseList,
      })
    }

    if (materialList.value.length <= 0) {
      data.goodList.forEach((good) => {
        addFormMaterial({
          code: good.code,
          id: good.id,
          name: good.name,
          specId: good.specId,
          specName: good.specName,
          type: good.type,
          unit: good.unit,
          price: good.price,
          storeQty: good.storeQty,
          freezeQty: good.freezeQty,
          isBom: false,
          warehouse: '',
          warehouseList: good.warehouse,
        })
      })
      data.bomList.forEach((bom) => {
        addFormMaterial({
          code: bom.code,
          id: bom.goodsId,
          name: bom.name,
          specId: bom.goodsSpecId,
          specName: bom.specName,
          type: bom.goodsType,
          unit: bom.unit,
          price: bom.price,
          storeQty: bom.stockQty,
          freezeQty: bom.freezeQty,
          isBom: true,
          warehouse: '',
          warehouseList: bom.warehouse,
        })
      })
    } else {
      const materialSpecIdList = materialList.value.map((item) => item.specId)
      const materialSpareIdList = materialList.value.map((item) => item.spareId)
      data.goodList.forEach((good) => {
        if (materialSpareIdList.includes(good.id) && materialSpecIdList.includes(good.specId)) {
          const applyMaterial = materialList.value.find(
            (item) => item.spareId === good.id && item.specId === good.specId,
          )
          if (applyMaterial) {
            _formMaterialList.push(cloneDeep(applyMaterial))
          }
        } else {
          addFormMaterial({
            code: good.code,
            id: good.id,
            name: good.name,
            specId: good.specId,
            specName: good.specName,
            type: good.type,
            unit: good.unit,
            price: good.price,
            storeQty: good.storeQty,
            freezeQty: good.freezeQty,
            isBom: false,
            warehouse: '',
            warehouseList: good.warehouse,
          })
        }
      })
      data.bomList.forEach((bom) => {
        if (
          materialSpareIdList.includes(bom.goodsId) &&
          materialSpecIdList.includes(bom.goodsSpecId)
        ) {
          const applyMaterial = materialList.value.find(
            (item) => item.spareId === bom.goodsId && item.specId === bom.goodsSpecId,
          )
          if (applyMaterial) {
            _formMaterialList.push(cloneDeep(applyMaterial))
          }
        } else {
          addFormMaterial({
            code: bom.code,
            id: bom.goodsId,
            name: bom.name,
            specId: bom.goodsSpecId,
            specName: bom.specName,
            type: bom.goodsType,
            unit: bom.unit,
            price: bom.price,
            storeQty: bom.stockQty,
            freezeQty: bom.freezeQty,
            isBom: true,
            warehouse: '',
            warehouseList: bom.warehouse,
          })
        }
      })
    }
    materialList.value = cloneDeep(_formMaterialList)
  }

  const handleDeleteClick = (goodIndex: number) => {
    materialList.value.splice(goodIndex, 1)
  }

  const handleApplyQtyChange = (materialIndex: number) => {
    const material = materialList.value[materialIndex]
    if (!material) {
      return
    }

    materialList.value[materialIndex].stockTipPopoverVisible = false
    if (material.applyQty > material.stock) {
      materialList.value[materialIndex].stockTipPopoverVisible = true
    }
  }

  const init = async () => {
    if (route.params.id) {
      await getSparePartApplyDetail(route.params.id as string)
      form.value = {
        area: sparePartApplyDetail.value.area || '',
        city: sparePartApplyDetail.value.city || '',
        province: sparePartApplyDetail.value.province || '',
        town: sparePartApplyDetail.value.town || '',
        code: sparePartApplyDetail.value.code || '',
        contactName: sparePartApplyDetail.value.contactName || '',
        contactPhone: sparePartApplyDetail.value.contactPhone || '',
        createType: sparePartApplyDetail.value.createType || 1,
        detailAddress: sparePartApplyDetail.value.detailAddress || '',
        id: sparePartApplyDetail.value.id || '',
        materialApplyParamList: [],
        networkId: sparePartApplyDetail.value.networkId || '',
        orderRemark: sparePartApplyDetail.value.orderRemark || '',
        receivingStoreId: sparePartApplyDetail.value.receivingStoreId || '',
        shippingStoreId: sparePartApplyDetail.value.shippingStoreId || '',
        status: sparePartApplyDetail.value.createType || 1,
        type: sparePartApplyDetail.value.type || 1,
        attachmentParamList: sparePartApplyDetail.value.attachmentList || [],
      }

      fileList.value = sparePartApplyDetail.value.attachmentList.map((url) => {
        return {
          file: null,
          url,
        }
      })

      getNetworkListParam.value.networkId = sparePartApplyDetail.value.networkId
      await getNetworkList()
      await getNetworkAmount(networkList.value[0].id)
      const firstNetwork = networkList.value[0]

      selectShowInfo.value = {
        receiveStoreName: sparePartApplyDetail.value.receivingStoreName,
        sendStoreName: sparePartApplyDetail.value.shippingStoreName,
        networkName: sparePartApplyDetail.value.networkName,
        freeAmount: networkAmountLimit.value.freeAmount || 0,
        networkCode: firstNetwork ? firstNetwork.code : '',
      }

      materialList.value = sparePartApplyDetail.value.materialApplyVoList.map((item) => {
        return {
          spareCode: item.spareCode,
          spareId: item.spareId,
          spareName: item.spareName,
          applyQty: item.qty,
          actualSendQty: item.actualQty,
          specId: item.specId,
          specName: item.specName,
          type: item.goodsType,
          unit: item.spareUnit,
          price: item.price || 0,
          remark: item.materialRemark,
          urgentLevel: item.urgency,
          stock: item.storeQty - item.freezeQty,
          stockTipPopoverVisible: false,
          id: item.id,
          isBom: item.isBoom === 1,
          warehouse: item.warehouse,
          warehouseList: item.warehouseList,
        }
      })
    } else {
      if (currentRole && currentRole.roleType === 1) {
        form.value.createType = 2
      }

      if (currentRole && currentRole.roleType === 2) {
        form.value.createType = 1
      }

      if (currentRole && currentRole.roleType === 2 && userStore.userInfo.networkId) {
        getNetworkListParam.value.networkId = userStore.userInfo.networkId
        await getNetworkList()
        if (networkList.value && networkList.value[0]) {
          const firstNetwork = networkList.value[0]
          selectShowInfo.value.freeAmount = firstNetwork.freeAmount
          handleNetworkOptionClick(firstNetwork)
        }
      }
    }
  }

  const handleNetworkOptionClick = async (data: NetworkAPIResponse.NetworkListItem) => {
    await getWarehouse(data.id)
    await getNetworkAmount(data.id)
    selectShowInfo.value.receiveStoreName = warehouse.value.storeName || ''
    form.value.receivingStoreId = warehouse.value.storeId || ''
    form.value.contactName = data.name || ''
    form.value.contactPhone = data.managerUserPhone || ''
    form.value.detailAddress = data.address || ''
    form.value.province = data.province || ''
    form.value.city = data.city || ''
    form.value.area = data.area || ''
    selectShowInfo.value.freeAmount = networkAmountLimit.value.freeAmount || 0
    form.value.networkId = data.id || ''
    selectShowInfo.value.networkName = data.name || ''
    selectShowInfo.value.networkCode = data.code || ''
    networkSelectPopoverVisible.value = false
  }

  const getSummaries = (param: {
    columns: TableColumnCtx<SparePartApplyFormMaterial>[]
    data: Array<SparePartApplyFormMaterial>
  }) => {
    const sums: Array<string> = []
    param.columns.forEach((item, index) => {
      if (index === 0) {
        sums[index] = '合计'
      }

      if (item.property === 'applyQty') {
        let total = 0
        param.data.forEach((item) => {
          total += item.applyQty || 0
        })
        sums[index] = `${total}`
      }

      if (item.property === 'totalPrice') {
        let total = 0
        param.data.forEach((item) => {
          total += (item.applyQty || 1) * (item.price || 0)
        })
        sums[index] = `￥${total.toFixed(2)}`
      }
    })
    return sums
  }

  const handleUploadAnnex = (file: UploadFile) => {
    if (!file.raw) return

    if (fileList.value.length >= 10) {
      HMessageBox.error('最多上传10个附件')
      return
    }

    if (file.raw.size / 1024 / 1024 > 50) {
      HMessageBox.error('文件大小不能超过50MB！')
      return
    }

    fileList.value.push({
      file: file.raw,
      url: URL.createObjectURL(file.raw),
    })
  }

  onBeforeUnmount(() => {
    document.removeEventListener('click', handleDocumentClick)
  })

  onMounted(() => {
    init()
  })
</script>

<template>
  <div
    v-loading="formSaveLoading || stockCheckLoading || getSparePartApplyDetailLoading"
    class="spare-part-form-page"
  >
    <div class="page-container">
      <div class="header">
        <div class="title">{{ route.params.id ? '修改配件申请单' : '新增配件申请单' }}</div>
        <div class="btn-group">
          <h-plain-button type="warning" @click="onSubmitClick(2)">保存并提交</h-plain-button>
          <h-plain-button type="primary" @click="onSubmitClick(1)">保存</h-plain-button>
          <h-button @click="closeThisPage">返回</h-button>
        </div>
      </div>
      <div class="form">
        <div class="title"> 基本信息 </div>
        <el-form
          ref="formInstance"
          label-position="top"
          inline-message
          :model="form"
          :rules="formRules"
        >
          <!-- 单据类型 -->
          <el-form-item v-if="currentRole && currentRole.roleType === 1" label="单据类型">
            <el-select v-model="form.type" placeholder="请选择单据类型">
              <el-option label="收费销售订单" :value="1" />
              <el-option label="免费销售订单(完全赠送)" :value="3" />
            </el-select>
          </el-form-item>

          <!-- 经销商编号 -->
          <el-form-item v-if="currentRole && currentRole.roleType === 1" label="经销商编号">
            <el-popover placement="bottom" :width="500" :visible="networkCodeSelectPopoverVisible">
              <template #reference>
                <el-input
                  v-model.trim="selectShowInfo.networkCode"
                  placeholder="请输入经销商编号"
                  @input="handleNetworkCodeInput"
                />
              </template>
              <el-table
                v-loading="getNetworkListLoading"
                :data="networkList"
                :border="true"
                :stripe="true"
                :max-height="350"
                @row-click="handleNetworkOptionClick"
              >
                <el-table-column width="50" type="index" label="序号" />
                <el-table-column
                  min-width="100"
                  property="name"
                  label="名称"
                  show-overflow-tooltip
                />
                <el-table-column width="200" property="name" label="地址" show-overflow-tooltip>
                  <template #default="{ row }">
                    {{ `${row.province} ${row.city} ${row.area} ${row.town} ${row.address}` }}
                  </template>
                </el-table-column>
              </el-table>
            </el-popover>
          </el-form-item>

          <!-- 经销商名称 -->
          <el-form-item
            v-if="currentRole && currentRole.roleType === 1"
            label="经销商名称"
            prop="networkId"
          >
            <el-popover placement="bottom" :width="500" :visible="networkSelectPopoverVisible">
              <template #reference>
                <el-input
                  v-model.trim="selectShowInfo.networkName"
                  placeholder="请输入经销商名称"
                  @input="handleNetworkInput"
                />
              </template>
              <el-table
                v-loading="getNetworkListLoading"
                :data="networkList"
                :border="true"
                :stripe="true"
                :max-height="350"
                @row-click="handleNetworkOptionClick"
              >
                <el-table-column width="50" type="index" label="序号" />
                <el-table-column
                  min-width="100"
                  property="name"
                  label="名称"
                  show-overflow-tooltip
                />
                <el-table-column width="200" property="name" label="地址" show-overflow-tooltip>
                  <template #default="{ row }">
                    {{ `${row.province} ${row.city} ${row.area} ${row.town} ${row.address}` }}
                  </template>
                </el-table-column>
              </el-table>
            </el-popover>
          </el-form-item>

          <!-- 可用额度 -->
          <el-form-item v-if="selectShowInfo.freeAmount !== null" label="可用额度">
            <el-input disabled :model-value="selectShowInfo.freeAmount" placeholder="可用额度" />
          </el-form-item>

          <!--收货仓-->
          <el-form-item label="收货仓" prop="receivingStoreId">
            <el-input
              disabled
              :model-value="selectShowInfo.receiveStoreName"
              placeholder="收货仓"
            />
          </el-form-item>

          <!--联系人姓名-->
          <el-form-item label="联系人姓名" prop="contactName">
            <el-input
              v-model.trim="form.contactName"
              maxlength="11"
              placeholder="请输入联系人姓名"
            />
          </el-form-item>

          <!--联系人手机号-->
          <el-form-item label="联系人手机号" prop="contactPhone">
            <el-input
              v-model.trim.number="form.contactPhone"
              maxlength="11"
              placeholder="请输入联系人手机号"
            />
          </el-form-item>

          <!--收货地址-->
          <el-form-item label="收货地址" prop="address">
            <single-address :address="address" @change="handleSingleAddressChange" />
          </el-form-item>

          <!--详细地址-->
          <el-form-item label="详细地址" prop="detailAddress">
            <el-input v-model.trim="form.detailAddress" placeholder="请输入详细地址" />
          </el-form-item>

          <!--单据备注-->
          <el-form-item label="单据备注">
            <el-input
              v-model.trim="form.orderRemark"
              placeholder="请输入单据备注"
              clearable
              type="textarea"
              maxlength="200"
              show-word-limit
              :resize="'both'"
            />
          </el-form-item>

          <!-- 附件 -->
          <el-form-item v-if="form.type == 3" label="附件">
            <template #label>
              <div>
                <span style="color: #f56c6c">*</span>
                <span>附件</span>
              </div>
            </template>

            <div class="file-upload-box">
              <el-upload
                v-if="fileList.length < 10"
                v-model="fileList"
                :auto-upload="false"
                :on-change="handleUploadAnnex"
                :show-file-list="false"
                accept="image/*"
                action="#"
                drag
                multiple
                class="file-upload"
              >
                <el-icon :size="24" color="#007cff">
                  <UploadFilled />
                </el-icon>
              </el-upload>
              <div class="file-list">
                <h-image
                  v-for="(file, fileIndex) in fileList"
                  :key="fileIndex"
                  :src="file.url"
                  :width="80"
                  :height="50"
                  :preview-src-list="fileList.map((file) => file.url)"
                  @del="fileList.splice(fileIndex, 1)"
                />
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="list">
        <div class="title">
          <div class="text">配件列表</div>
        </div>
        <div class="table">
          <el-table
            :border="true"
            :stripe="true"
            :resize="true"
            :data="materialList"
            show-summary
            height="100%"
            :summary-method="getSummaries"
          >
            <!-- 序号 -->
            <el-table-column type="index" label="序号" width="50" :align="'center'" fixed="left" />

            <!-- 配件编号 -->
            <el-table-column label="配件编号" prop="spareCode" width="100" />

            <!-- 配件名称 -->
            <el-table-column
              show-overflow-tooltip
              label="配件名称"
              prop="spareName"
              min-width="140"
            />

            <!-- 申请数量 -->
            <el-table-column width="140" prop="applyQty">
              <template #header>
                <div class="multiple-table-column-header">
                  <div class="text">申请数量</div>
                  <el-popover :width="196" :visible="allQtyInputPopoverVisible" placement="top">
                    <template #reference>
                      <h-plain-button :height="22" :padding-lr="4" @click.stop="onQtyMultipleClick">
                        批量
                      </h-plain-button>
                    </template>

                    <div class="all-apply-qty-popover" @click.stop="">
                      <el-input
                        v-model.trim.number="allApplyQty"
                        style="width: 120px"
                        placeholder="请输入数量"
                      />
                      <h-plain-button @click="onQtyMultipleConfirmClick">确定</h-plain-button>
                    </div>
                  </el-popover>
                </div>
              </template>

              <template #default="{ row, $index }">
                <div
                  style="
                    display: flex;
                    flex-direction: column;
                    row-gap: 4px;
                    justify-content: flex-start;
                  "
                >
                  <el-input
                    v-model.trim.number="row.applyQty"
                    placeholder="请输入申请数量"
                    @input="handleApplyQtyChange($index)"
                  />
                  <div v-if="row.stockTipPopoverVisible" style="color: #f56c6c; font-weight: bold">
                    申请数量大于可用量
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column v-if="form.type === 3" label="库存地址" width="120">
              <template #default="{ row }">
                <el-select v-model="row.warehouse" placeholder="请选择库存地址">
                  <el-option
                    v-for="(option, optionIndex) in row.warehouseList"
                    :key="optionIndex"
                    :label="option"
                    :value="option"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 规格 -->
            <el-table-column label="规格" prop="specName" width="120" />

            <!-- 分类 -->
            <el-table-column label="分类" prop="type" width="120" />

            <!-- 单位 -->
            <el-table-column label="单位" prop="unit" width="80" />

            <!-- 单价 -->
            <el-table-column label="单价" prop="price" width="100">
              <template #default="{ row }"> ￥{{ row.price.toFixed(2) }} </template>
            </el-table-column>

            <!-- 金额 -->
            <el-table-column label="金额" width="120" prop="totalPrice">
              <template #default="{ row }">
                ￥{{ (row.price * row.applyQty).toFixed(2) }}
              </template>
            </el-table-column>

            <!-- 备注 -->
            <el-table-column label="备注" width="160">
              <template #default="{ row }">
                <el-input v-model.trim="row.remark" placeholder="请输入备注" />
              </template>
            </el-table-column>

            <!-- 紧急程度 -->
            <el-table-column label="紧急程度" width="120">
              <template #default="{ row }">
                <el-select v-model="row.urgentLevel">
                  <el-option :value="1" label="一般" />
                  <el-option :value="2" label="紧急" />
                  <el-option :value="3" label="非常紧急" />
                </el-select>
              </template>
            </el-table-column>

            <!-- 操作 -->
            <el-table-column width="100" :align="'center'" fixed="right">
              <template #header>
                <h-link @click="sparePartSelectModalVisible = true">点击选择配件</h-link>
              </template>
              <template #default="{ $index }">
                <h-link type="error" @click="handleDeleteClick($index)">删除</h-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <spare-part-select-modal
      v-model="sparePartSelectModalVisible"
      :good-selection="materialSpareIdAndSpecIdList"
      @update="handleSparePartSelectModalGoodSelect"
    />
  </div>
</template>

<style scoped lang="scss">
  .file-upload-box {
    display: flex;

    .file-upload {
      width: 80px;
      height: 50px;

      :deep(.el-upload) {
        width: 100%;
        height: 100%;

        .el-upload-dragger {
          display: flex;
          align-items: center;
          column-gap: 5px;
          width: 100%;
          height: 100%;
          box-sizing: border-box;
          padding: 0;
          background: none;
          justify-content: center;
        }
      }
    }

    .file-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
  }

  .multiple-table-column-header {
    display: flex;
    align-items: center;
    column-gap: 4px;

    .text {
      white-space: nowrap;
    }
  }

  .all-apply-qty-popover {
    display: flex;
    justify-content: space-between;
  }

  .spare-part-form-page {
    width: 100%;
    height: calc(100vh - 92px);
    box-sizing: border-box;
    padding: 12px;

    .page-container {
      width: 100%;
      height: 100%;
      background-color: #fff;
      box-sizing: border-box;
      padding: 12px;
      display: flex;
      flex-direction: column;

      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px dotted #d4d4d4;
        padding-bottom: 12px;
        margin-bottom: 12px;

        .title {
          font-size: 16px;
          font-weight: bold;
        }

        .btn-group {
          display: flex;
          column-gap: 8px;
        }
      }

      .form {
        .title {
          font-size: 14px;
          font-weight: bold;
        }

        :deep(.el-form) {
          display: grid;
          grid-template-columns: repeat(5, 1fr);
          row-gap: 12px;
          column-gap: 24px;

          .el-form-item {
            width: 100%;

            .el-form-item__label {
              margin: 0;
            }

            .el-form-item__content {
              .el-textarea {
                .el-textarea__inner {
                  width: 100% !important;
                  max-height: 200px;
                  height: 28px;
                }
              }

              .el-form-item__error {
                margin: 0;
              }
            }
          }
        }
      }

      .list {
        display: flex;
        flex-direction: column;
        row-gap: 4px;
        margin-top: 12px;
        flex: 1;
        height: 0;

        .title {
          display: flex;
          column-gap: 2px;
          align-items: center;

          .text {
            font-size: 14px;
            font-weight: bold;
          }
        }

        .table {
          max-height: calc(100% - 19px - 4px);
        }
      }
    }
  }
</style>
